package com.sujeet.learning.sort;

import java.util.Arrays;
import java.util.ArrayList;

import static com.sujeet.learning.common.utils.BasicUtils.show;

public class Bubble {

	public static void main(String[] args) {
		// Arrays.asList(1, 2, 3, 4, 2, 10, 91, 7, 5, 6, 7)
		ArrayList<Integer> sample = 
				new ArrayList<Integer>(Arrays.asList(10,9,8,7,6,5,4,3,2,1,12));
		show("sample: " + sample);
		show("size: " + sample.size());
		bubbleSort(sample);
		
	}
	
	private static void bubbleSort(ArrayList<Integer> sample) {
		Long start = System.currentTimeMillis();
		Integer passes = 0;
		Integer totalSwaps = 0;
		boolean swapped = true;
		while(swapped) {
			int i = 0; int swapCount = 0;
			while ((i+1) < sample.size()) {
				if (sample.get(i) < sample.get(i+1)) {
					Integer tmp = sample.get(i);
					sample.set(i, sample.get(i+1));
					sample.set((i+1), tmp);				
					++swapCount;
				}
				++i;
			}
			if (swapCount == 0) swapped = false;
			++passes;
			totalSwaps = totalSwaps + swapCount;
			show("pass# " + passes);
			show(sample);
		}
		Long stop = System.currentTimeMillis();
		show("total passes: " + passes);
		show("total swaps: " + totalSwaps);
		show("time taken ~= " + (stop - start));
	}
	
	private static void someSort(ArrayList<Integer> sample) {
		Integer passes = 0;
		for (int i = 0; i < sample.size(); i++) {
			for (int j = i + 1; j < sample.size(); j++) {
				if (sample.get(i) < sample.get(j)) {
					Integer tmp = sample.get(i);
					sample.set(i, sample.get(j));
					sample.set(j, tmp);
					show(sample);
					++passes;
				}
			}
		}
		show(passes);
	}
}
